package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.User;
import com.itheima.service.IUserSevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;

import static com.itheima.controller.Code.*;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private IUserSevice iUserSevice;
    @Autowired
    private UserMapper userMapper;



	//分页查询用户
    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable  int currentPage,@PathVariable int pageSize) throws IOException {
        IPage<User> page = new Page<>(currentPage, pageSize);
        userMapper.selectPage(page, null);
        List<User> rows = page.getRecords();
//        System.out.println(rows);
        long totalCount = page.getTotal();
//        System.out.println(totalCount);
        PageBean pageBean = new PageBean(rows, totalCount);
        Result result = new Result(GET_OK,pageBean,"分页成功");
        System.out.println(result);
        return result;
    }
    /**
     * 保存用户
     * @param user 用户数据
     */
    @PostMapping
    public Result add(@RequestBody  User user) {
        System.out.println("user = " + user);
        int i = userMapper.insert(user);
        if (i == 1) {
            return new Result(SAVE_OK, "", "添加成功");
        } else return new Result(SAVE_ERR, "", "添加失败");
    }
    /**
     * 根据用户id查询用户
     * @param id 用户id
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        int i = userMapper.deleteById(id);
        if (i == 1) {
            return new Result(DELETE_OK, "", "删除成功");
        }
        else  return new Result(DELETE_ERR,"","删除失败");
    }

    /**
     * 更新用户
     * @param user 用户数据
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        int i = userMapper.update(user, lqw.eq(User::getId, user.getId()));
        if(i==1){
            return new Result(UPDATE_OK,user,"修改成功");
        }
        else return new Result(UPDATE_ERR,user,"修改失败");
    }
}
